package com.yc.scott.ui;

import java.awt.Component;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JList;

import com.yc.jdbc.DBHelper;

public class DBComboBox extends JComboBox<Map<String,Object>>{
	private static final long serialVersionUID = 1L;
	
	String sql;
	String displayColumn;
	List<Map<String,Object>> list;

	public DBComboBox(String sql, String displayColumn) {
		super();
		this.sql = sql;
		this.displayColumn = displayColumn;
		list = DBHelper.selectList(sql);
		list.forEach(this::addItem);
		
		// 加入渲染对象
		this.setRenderer(new DefaultListCellRenderer() {
			private static final long serialVersionUID = 1L;

			@Override
			public Component getListCellRendererComponent(
					JList<?> list, Object value, int index, boolean isSelected,
					boolean cellHasFocus) {
				@SuppressWarnings("unchecked")
				Map<String,Object> map = (Map<String, Object>) value;
//				setText(map.get(displayColumn.toUpperCase()).toString());
				// map.get(displayColumn.toUpperCase()) 有可能是 null 值
				// 这里有可能出现空指针异常
				String svalue = (String) map.get(displayColumn.toUpperCase());
				setText(svalue);
				// 处理选中状态
                if (isSelected) {
                    setBackground(list.getSelectionBackground());
                    setForeground(list.getSelectionForeground());
                } else {
                    setBackground(list.getBackground());
                    setForeground(list.getForeground());
                }
				return this;
			}
			
		});
		
	}
	
	// 选择指定的项目
	// Predicate 断言函数接口
	public void select(Predicate<Map<String,Object>> predicate) {
		for (int i = 0; i < list.size(); i++) {
			Map<String,Object> row = list.get(i);
			// 判断是否相等
			if(predicate.test(row) == true) {
				// 选择当前选项
				this.setSelectedIndex(i);
				return;
			}
		}
	}
	
	
	

}
